<template>
  <t-dialog
    :header="header"
    placement="center"
    :visible.sync="visible"
    :onClose="closeDialog"
    width="80%"
    top="48px"
    :closeOnEscKeydown="false"
    :closeOnOverlayClick="false"
    :footer="edit"
    >
    <template #footer>
      <t-button :loading="btnLoading" theme="success" @click="onSubmit(0)">暂存</t-button>
      <t-tooltip content="提交后不可再编辑会进入审批流程">
        <t-button :loading="btnLoading" :disabled="isCommit"  theme="primary" @click="onSubmit(1)">提交</t-button>
      </t-tooltip>
    </template>
    <t-loading :text="formLoadingText" size="medium" :loading="formLoading" showOverlay>
      <template #indicator>
        <t-icon v-if="formLoadingText === '数据读取中...'" name="loading" slot="icon"/>
        <t-icon v-else name="error-circle-filled" slot="icon"/>
      </template>
      <t-form
        labelAlign="left"
        labelWidth="90px"
        :data="formData"
        ref="form"
        :colon="true"
        :rules="edit ? rules : {}"
      >
        <t-card hover-shadow v-for="(detail, index) in formData.projectDetails" :key="detail.tid">
          <t-row>
            <t-col :span="8">
              <t-form-item label="项目名称" :name="`projectDetails[${index}].projectName`">
                <t-input v-if="edit" v-model="formData.projectDetails[index].projectName" placeholder="请输入项目名称"></t-input>
                <span v-else>{{formData.projectDetails[index].projectName}}</span>
              </t-form-item>
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="4">
              <t-form-item label="合同开始时间" :name="`projectDetails[${index}].startDate`" :label-width="120">
                <t-date-picker v-if="edit" v-model="formData.projectDetails[index].startDate" placeholder="请选择合同开始时间" />
                <span v-else>{{formData.projectDetails[index].startDate}}</span>
              </t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item label="合同终止时间" :name="`projectDetails[${index}].completeDate`" :label-width="120">
                <t-date-picker v-if="edit" v-model="formData.projectDetails[index].completeDate" placeholder="请选择合同终止时间" />
                <span v-else>{{formData.projectDetails[index].completeDate}}</span>
              </t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item label="实际完成时间" :name="`projectDetails[${index}].actualCompleteDate`" :label-width="120">
                <t-date-picker v-if="edit" v-model="formData.projectDetails[index].actualCompleteDate" placeholder="请选择实际完成时间" />
                <span v-else>{{formData.projectDetails[index].actualCompleteDate}}</span>
              </t-form-item>
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="5">
              <t-form-item label="项目进展" :name="`projectDetails[${index}].projectProgress`">
                <t-select v-if="edit" v-model="formData.projectDetails[index].projectProgress" :options="dict.type.project_progress" placeholder="请选择项目进展" />
                <span v-else>{{formData.projectDetails[index].projectProgress|filterByDict(dict.type.project_progress)}}</span>
              </t-form-item>
            </t-col>
            <t-col :span="5" :offset="1">
              <t-form-item label="项目来源" :name="`projectDetails[${index}].projectSource`">
                <t-select v-if="edit" v-model="formData.projectDetails[index].projectSource" :options="dict.type.project_source" placeholder="请选择项目来源" />
                <span v-else>{{formData.projectDetails[index].projectSource|filterByDict(dict.type.project_source)}}</span>
              </t-form-item>
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="5">
              <t-form-item label="项目类别" :name="`projectDetails[${index}].projectCategory`">
                <t-tree-select 
                  v-if="edit"
                  v-model="formData.projectDetails[index].projectCategory"
                  :data="projectCategory"
                  :treeProps="{ keys: { value: 'id' } }"
                  filterable
                  clearable
                  placeholder="请选择项目类别"
                />
                <span v-else>{{formData.projectDetails[index].projectCategory|showLabel(projectCategory)}}</span>
              </t-form-item>
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="5">
              <t-form-item label="重大研发任务" :name="`projectDetails[${index}].majorTask`" :label-width="120">
                <t-select v-if="edit" v-model="formData.projectDetails[index].majorTask" :options="dict.type.major_task" placeholder="请选择重大研发任务" />
                <span v-else>{{formData.projectDetails[index].majorTask|filterByDict(dict.type.major_task)}}</span>
              </t-form-item>
            </t-col>
            <t-col :span="5" :offset="1">
              <t-form-item label="重点研发方向" :name="`projectDetails[${index}].majorDirection`" :label-width="120">
                <t-select v-if="edit" v-model="formData.projectDetails[index].majorDirection" :options="dict.type.major_direction" placeholder="请选择重点研发方向" />
                <span v-else>{{formData.projectDetails[index].majorDirection|filterByDict(dict.type.major_direction)}}</span>
              </t-form-item>
            </t-col>
          </t-row>
          <t-row><b>本年资金支出</b></t-row>
          <t-row>
            <t-col :span="4">
              <t-form-item label="政府资金" :name="`projectDetails[${index}].zfzj`">
                <t-input-adornment v-if="edit" append="万元">
                  <t-input-number v-model="formData.projectDetails[index].zfzj"  placeholder="请输入政府资金" theme="normal" />
                </t-input-adornment>
                <span v-else>{{formData.projectDetails[index].zfzj}} 万元</span>
              </t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item label="依托工程配套资金" :name="`projectDetails[${index}].ytgcptzj`" :label-width="145">
                <t-input-adornment v-if="edit" append="万元">
                  <t-input-number v-model="formData.projectDetails[index].ytgcptzj"  placeholder="请输入依托工程配套资金" theme="normal" />
                </t-input-adornment>
                <span v-else>{{formData.projectDetails[index].ytgcptzj}} 万元</span>
              </t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item label="其他资金" :name="`projectDetails[${index}].qtzj`">
                <t-input-adornment v-if="edit" append="万元">
                  <t-input-number v-model="formData.projectDetails[index].qtzj"  placeholder="请输入其他资金" theme="normal" />
                </t-input-adornment>
                <span v-else>{{formData.projectDetails[index].qtzj}} 万元</span>
              </t-form-item>
            </t-col>
          </t-row>
          <t-row><b>本年折合全时工作量</b></t-row>
          <t-row>
            <t-col :span="4">
              <t-form-item label="高级职称" :name="`projectDetails[${index}].gjzc`">
                <t-input-adornment v-if="edit" append="人年">
                  <t-input-number v-model="formData.projectDetails[index].gjzc"  placeholder="请输入高级职称" theme="normal" />
                </t-input-adornment>
                <span v-else>{{formData.projectDetails[index].gjzc}} 人年</span>
              </t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item label="中级职称" :name="`projectDetails[${index}].zjzc`">
                <t-input-adornment v-if="edit" append="人年">
                  <t-input-number v-model="formData.projectDetails[index].zjzc"  placeholder="请输入中级职称" theme="normal" />
                </t-input-adornment>
                <span v-else>{{formData.projectDetails[index].zjzc}} 人年</span>
              </t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item label="其他职称" :name="`projectDetails[${index}].qtzc`">
                <t-input-adornment v-if="edit" append="人年">
                  <t-input-number v-model="formData.projectDetails[index].qtzc"  placeholder="请输入其他职称" theme="normal" />
                </t-input-adornment>
                <span v-else>{{formData.projectDetails[index].qtzc}} 人年</span>
              </t-form-item>
            </t-col>
          </t-row>
  
          <t-row>
            <t-button v-if="edit" variant="dashed" theme="danger" @click="delLine(index)">删除此行</t-button>
          </t-row>
        </t-card>
        <t-card hover-shadow v-if="edit">
          <t-button variant="dashed" theme="primary" @click="addLine">
            <t-icon name="add" slot="icon" />
            添加一行
          </t-button>
        </t-card>
      </t-form>
    </t-loading>
  </t-dialog>
</template>

<script>

function getLabelByTree(id, tree) {
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    if (node.id === id) return node.label
    if (node.children) {
      const label = getLabelByTree(id, node.children)
      if (label !== '未知') return label
    }
  }
  return '未知'
}
export default {
  name: 'TabTechnologyProjecForm',
  filters: {
    showLabel: (val, projectCategory) => getLabelByTree(val, projectCategory)
  },
  props: {
    edit: { type: Boolean, default: true },
    infoId: { type: Number, default: -1 }
  },
  dicts: ['project_progress', 'project_source', 'major_task', 'major_direction'],
  data() {
    return {
      visible: true,
      btnLoading: false,
      formLoading: true,
      formLoadingText: '数据读取中...',
      header: '',
      formData: {
        projectDetails: [
          // {
          //   projectName: undefined,
          //   startDate: undefined,
          //   completeDate: undefined,
          //   actualCompleteDate: undefined,
          //   project_progress: undefined,
          //   projectSource: undefined,
          //   projectCategory: undefined,
          //   majorTask: undefined,
          //   majorDirection: undefined,
          //   zfzj: undefined,
          //   ytgcptzj: undefined,
          //   qtzj: undefined,
          //   gjzc: undefined,
          //   zjzc: undefined,
          //   qtzc: undefined,
          // }
        ],
        approveStatus: '1',
      },
      rules: {
        // list
        projectName: [{ required: true, message: '项目名称不能为空' }],
        startDate: [{ required: true, message: '合同开始时间不能为空' }],
        completeDate: [{ required: true, message: '合同终止时间不能为空' }],
        actualCompleteDate: [{ required: true, message: '实际完成时间不能为空' }],
        projectProgress: [{ required: true, message: '项目进展不能为空' }],
        projectSource: [{ required: true, message: '项目来源不能为空' }],
        projectCategory: [{ required: true, message: '项目类别不能为空' }],
        majorTask: [{ required: true, message: '重大研发任务不能为空' }],
        majorDirection: [{ required: true, message: '重点研发方向不能为空' }],
        zfzj: [{ required: true, message: '政府资金不能为空' }],
        ytgcptzj: [{ required: true, message: '依托工程配套资金不能为空' }],
        qtzj: [{ required: true, message: '其他资金不能为空' }],
        gjzc: [{ required: true, message: '高级职称不能为空' }],
        zjzc: [{ required: true, message: '中级职称不能为空' }],
        qtzc: [{ required: true, message: '其他职称不能为空' }],
      },
      projectCategory: []
    }
  },
  computed: {
    isCommit() {
      return this.formData.approveStatus !== '1'
    },
    labelWidth() {
      return '120px'
    }
  },
  created() {
    this.getProjectCategroy()
    if (this.edit) {
      if (this.infoId === -1) {
        this.header = '添加信息记录'
        this.formLoading = false
      } else {
        this.header = '修改信息内容'
        this.getDetail()
      }
    } else if (this.infoId === -1) {
      this.header = '信息错误！！！'
      this.formLoadingText = '信息错误，请联系管理员'
    } else {
      this.header = '查看信息内容'
      this.getDetail()
    }
  },
  methods: {
    async getProjectCategroy() {
      try {
        const { data } = await this.$api.kjxm.project.planCategoryDeclareTree()
        this.projectCategory = data
        this.formLoading = false
      } catch (e) {
        this.$message.error('初始化数据[项目类别]获取失败，请联系管理员！')
      }
    },
    // 查看和修改时获取详情
    async getDetail() {
      try {
        const { data } = await this.$api.kjtjdc.table.projectInfo.getInfoById(this.infoId);
        this.formData = data;
        this.formLoading = false
      } catch (e) {
        this.formLoadingText = e
        this.$message.error('数据获取失败，请稍后再试！')
      }
    },
    async onSubmit(isCommit) {
      this.btnLoading = true
      let validRes
      try {
        validRes = await this.$refs.form.validate()
      // eslint-disable-next-line no-empty
      } catch (e) {}
      if (validRes !== true) {
        this.$message.warning('请完善表单')
        this.btnLoading = false
        return
      }
      let action = 'edit'
      if (this.infoId === -1) {
        // 新增
        action = 'add'
      }
      if (isCommit) {
        // 提交
        this.formData.approveStatus = '2'
      } else {
        // 暂存
        this.formData.approveStatus = '1'
      }
      try {
        const { code, msg } = await this.$api.kjtjdc.table.projectInfo[action](this.formData);
        if (code === 200) {
          this.$message.success(`${isCommit?'提交':'暂存'}信息成功！`)
          this.btnLoading = false
          this.$emit('update:visible', false);
          this.$emit('reload');
        } else {
          throw msg
        }
      } catch (e) {
        this.$message.error(e)
        this.btnLoading = false
      }
    },
    closeDialog() {
      this.$refs.form.reset();
      this.$emit('update:visible', false);
    },
    addLine() {
      const tid = Math.random().toString(32).substring(2, 7)
      this.formData.projectDetails.push({tid})
    },
    delLine(idx) {
      this.formData.projectDetails.splice(idx, 1)
    }
  }
};
</script>

<style lang="less" scoped>
.t-form {
  max-height: 70vh;
  overflow: auto;
  padding: 5px 10px 8px 0;
}
.t-form::-webkit-scrollbar {
    width: 7px;
    background: rgb(0 0 0 / 1%);
}
.t-form::-webkit-scrollbar-thumb {
    border-radius: 6px;
    border: 4px solid rgb(0 0 0 / 10%);
    background-clip: content-box;
    background-color: rgb(0 0 0 / 10%);
}
.t-form__item {
  margin: 0 35px 0 0;
}
.t-row {
  margin-bottom: 20px;
}
.t-row:last-of-type {
  margin-bottom: 0;
}
.t-card {
  margin-bottom: 10px;
}
</style>
